/**
 * @工程名称：cargo-api
 * @程序包名：com.shenzhenair.cargo.support.http
 * @程序类名：RSAUtils.java
 * @创建日期：2019年8月7日
 */
package com.platform.common.security.utils;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * @功能说明：
 * RSA公钥/私钥/签名工具包
 * 字符串格式的密钥在未在特殊说明情况下都为BASE64编码格式<br/>
 * 由于非对称加密速度极其缓慢，一般文件不使用它来加密而是使用对称加密，<br/>
 * 非对称加密算法可以用来对对称加密的密钥加密，这样保证密钥的安全也就保证了数据的安全
 * @创建人员：zhenghb
 * @变更记录：<BR>
 * 1、2019年8月7日 zhenghb 新建类
 */
public class AirlineRSAUtils {

	/**
	 * 密钥长度，DH算法的默认密钥长度是1024
	 * 密钥长度必须是64的倍数，在512到65536位之间
	 */
	private static final int KEY_SIZE = 1024;

	/**
	 * 加密算法RSA
	 */
	private static final String KEY_ALGORITHM = "RSA";
	/**
	 * 获取公钥的key
	 */
	private static final String PUBLIC_KEY = "RSAPublicKey";
	/**
	 * 获取私钥的key
	 */
	private static final String PRIVATE_KEY = "RSAPrivateKey";
	/**
	 * 签名算法
	 */
	private static final String SIGNATURE_ALGORITHM = "MD5withRSA";
	/**
	 * 常量0
	 */
	private static final int ZERO = 0;
	/**
	 * RSA最大加密明文最大大小
	 */
	private static final int MAX_ENCRYPT_BLOCK = 117;
	/**
	 * RSA最大解密密文最大大小
	 * 当密钥位数为1024时,解密密文最大是 128
	 * 当密钥位数为2048时需要改为 256 不然会报错（Decryption error）
	 */
	private static final int MAX_DECRYPT_BLOCK = 128;

	/**
	 * 初始化密钥对
	 *
	 * @return Map 甲方密钥的Map
	 */
	public static Map<String, Object> initKey(int keySize) throws Exception {
		// 实例化密钥生成器
		KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
		// 初始化密钥生成器
		keyPairGenerator.initialize(keySize);
		// 生成密钥对
		KeyPair keyPair = keyPairGenerator.generateKeyPair();
		// 甲方公钥
		RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
		// 甲方私钥
		RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
		// 将密钥存储在map中
		Map<String, Object> keyMap = new HashMap<String, Object>();
		keyMap.put(PUBLIC_KEY, publicKey);
		keyMap.put(PRIVATE_KEY, privateKey);
		return keyMap;
	}

	/**
	 * @函数名称：initKey
	 * @创建日期：2019年8月8日
	 * @功能说明：生成密钥对(公钥和私钥)
	 * @参数说明：
	 * @返回说明：Map<String,Object>
	 */
	public static Map<String, Object> initKey() throws Exception {
		return initKey(KEY_SIZE);
	}

	/**
	 * @函数名称：encryptByPublicKey
	 * @创建日期：2019年8月8日
	 * @功能说明：公钥加密
	 * @参数说明：data      源数据
	 * publicKey 公钥(BASE64编码)
	 * @返回说明：byte[]
	 */
	public static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception {
		byte[] keyBytes = Base64Utils.decode(publicKey);
		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		return encrypt(data, KeyFactory.getInstance(KEY_ALGORITHM), keyFactory.generatePublic(x509KeySpec));
	}

	/**
	 * @函数名称：encryptByPrivateKey
	 * @创建日期：2019年8月8日
	 * @功能说明：私钥加密
	 * @参数说明：data       源数据
	 * privateKey 私钥(BASE64编码)
	 * @返回说明：byte[]
	 */
	public static byte[] encryptByPrivateKey(byte[] data, String privateKey) throws Exception {
		byte[] keyBytes = Base64Utils.decode(privateKey);
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
		return encrypt(data, keyFactory, privateK);
	}

	/**
	 *
	 * @函数名称：decryptByPrivateKey
	 * @创建日期：2019年8月8日
	 * @功能说明：私钥解密
	 * @参数说明：encryptedData 已加密数据
	 * @返回说明：byte[]
	 */
	public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) throws Exception {
		byte[] keyBytes = Base64Utils.decode(privateKey);
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		return decrypt(encryptedData, keyFactory, keyFactory.generatePrivate(pkcs8KeySpec));
	}

	/**
	 * @函数名称：decryptByPublicKey
	 * @创建日期：2019年8月8日
	 * @功能说明：公钥解密
	 * @参数说明：encryptedData 已加密数据
	 * publicKey     公钥(BASE64编码)
	 * @返回说明：byte[]
	 */
	public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) throws Exception {
		byte[] keyBytes = Base64Utils.decode(publicKey);
		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		Key publicK = keyFactory.generatePublic(x509KeySpec);
		return decrypt(encryptedData, keyFactory, publicK);

	}

	/**
	 * @函数名称：sign
	 * @创建日期：2019年8月8日
	 * @功能说明：用私钥对信息生成数字签名
	 * @参数说明：data       已加密数据
	 * privateKey 私钥(BASE64编码)
	 * @返回说明：String
	 */
	public static String sign(byte[] data, String privateKey) throws Exception {
		byte[] keyBytes = Base64Utils.decode(privateKey);
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
		Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
		signature.initSign(privateK);
		signature.update(data);
		return Base64Utils.encode(signature.sign());
	}

	/**
	 * @函数名称：verify
	 * @创建日期：2019年8月8日
	 * @功能说明：校验数字签名
	 * @参数说明：data      已加密数据
	 * publicKey 公钥(BASE64编码)
	 * @返回说明：boolean
	 */
	public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {
		byte[] keyBytes = Base64Utils.decode(publicKey);
		X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		PublicKey publicK = keyFactory.generatePublic(keySpec);
		Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
		signature.initVerify(publicK);
		signature.update(data);
		return signature.verify(Base64Utils.decode(sign));
	}

	/**
	 * @函数名称：getPrivateKey
	 * @创建日期：2019年8月8日
	 * @功能说明：获取私钥
	 * @参数说明：keyMap 密钥对
	 * @返回说明：String
	 */
	public static String getPrivateKey(Map<String, Object> keyMap) throws Exception {
		Key key = (Key) keyMap.get(PRIVATE_KEY);
		return Base64Utils.encode(key.getEncoded());
	}

	/**
	 * @函数名称：getPublicKey
	 * @创建日期：2019年8月8日
	 * @功能说明：获取公钥
	 * @参数说明：keyMap 密钥对
	 * @返回说明：String
	 */
	public static String getPublicKey(Map<String, Object> keyMap) throws Exception {
		Key key = (Key) keyMap.get(PUBLIC_KEY);
		return Base64Utils.encode(key.getEncoded());
	}

	/**
	 * @函数名称：decrypt
	 * @创建日期：2019年8月8日
	 * @功能说明：解密公共方法
	 * @参数说明：
	 * @返回说明：byte[]
	 */
	private static byte[] decrypt(byte[] data, KeyFactory keyFactory, Key key) throws Exception {

		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.DECRYPT_MODE, key);
		return encryptAndDecrypt(data, cipher, MAX_DECRYPT_BLOCK);
	}

	/**
	 * @函数名称：encrypt
	 * @创建日期：2019年8月8日
	 * @功能说明：加密公共方法
	 * @参数说明：
	 * @返回说明：byte[]
	 */
	private static byte[] encrypt(byte[] data, KeyFactory keyFactory, Key key) throws Exception {
		// 对数据加密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.ENCRYPT_MODE, key);
		return encryptAndDecrypt(data, cipher, MAX_ENCRYPT_BLOCK);
	}

	/**
	 * @函数名称：encryptAndDecrypt
	 * @创建日期：2019年8月8日
	 * @功能说明：加密解密分段处理公共方法
	 * @参数说明：
	 * @返回说明：byte[]
	 */
	private static byte[] encryptAndDecrypt(byte[] data, Cipher cipher, int maxSize) throws Exception {
		int inputLen = data.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = ZERO;
		byte[] cache;
		int i = ZERO;
		// 对数据分段加密
		while (inputLen - offSet > ZERO) {
			if (inputLen - offSet > maxSize) {
				cache = cipher.doFinal(data, offSet, maxSize);
			} else {
				cache = cipher.doFinal(data, offSet, inputLen - offSet);
			}
			out.write(cache, ZERO, cache.length);
			i++;
			offSet = i * maxSize;
		}
		byte[] encryptedData = out.toByteArray();
		out.close();
		return encryptedData;
	}

//	public static void main(String[] args) throws Exception {

//		KmgManifestReq req = new KmgManifestReq();
//		KmgManifestInfo info = new KmgManifestInfo();
//		List<KmgManifestGoods> goodsList = new ArrayList<>();
//		KmgManifestGoods goods = new KmgManifestGoods();
//		goods.setAirwayBillNo("833-14184192");
//		goods.setAgentName("明龙有限公司");
//		goods.setTopGoodsKind("C");
//		goods.setGoodsKind("普通货物");
//		goods.setGoodsName("狗");
//		goods.setPackType("纸箱");
//		goods.setBillWeight(120.0);
//		goods.setBillPieces(1);
//		goods.setBillSize(1.0);
//		goods.setIsPart("0");
//		goods.setIsInternational("0");
//		goods.setIsTransfercargo("1");
//		goods.setTakeoffStationC3("KMG");
//		goods.setTransferStationC3("HRB");
//		goods.setDestinationC3("PEK");
//		goods.setRemark("活体");
//
//		goodsList.add(goods);
//		info.setDetail(goodsList);
//
//		info.setFlightId("aabbccdd");
//		info.setFlightNo("KY8245");
//		info.setFlightDate("2019-01-01");
//		info.setPlaneNo("B1331");
//		info.setTakeoffStationC3("KMG");
//		info.setTransferStationC3("TNA");
//		info.setDestinationC3("HRB");
//
//		req.setTimestamp("1556014747893");

//		String str = "";

		// 生成公钥与私钥
		// Map<String, Object> initKeyMap = RSAUtils.initKey(1024);
		// 公钥
		// String publicKey = RSAUtils.getPublicKey(initKeyMap);
		// 私钥
		// String privateKey = RSAUtils.getPrivateKey(initKeyMap);
		// System.out.println("公钥 长度: " + publicKey.length() + " 值: " + publicKey);
		// System.out.println("私钥 长度: " + privateKey.length() + " 值: " + privateKey);

		// String publicKey =
		// "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCyrZxAHEDnHtzeN48KCkbqVJpCtLNr/KB9mzJ9KFQxYJJ7yLqnvd7s2IHLsnAN4abXJaILEVYb3zU0KQDVIiO+2sDzZ+5sQYQctS9H1EVC8Cn9vIoFDqxckKu77tcrmgNk/26ovNVDklL8dZOpC3mXtw3/Jy/CQ69zHikcmird5wIDAQAB";

//		String privateKey = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBALKtnEAcQOce3N43jwoKRupUmkK0s2v8oH2bMn0oVD" +
//                "FgknvIuqe93uzYgcuycA3hptclogsRVhvfNTQpANUiI77awPNn7mxBhBy1L0fURULwKf28igUOrFyQq7vu1yuaA2T/bqi81UOSUvx1" +
//                "k6kLeZe3Df8nL8JDr3MeKRyaKt3nAgMBAAECgYBhpRzZsFcLt0MOsaAa5YjhsIBo6eWPowx1+CV8Xli8b0E+InFXEB1Oo/cywX4ZJ/" +
//                "MMaoWGtN+w9adWrP3GfBS54yspD7gCc5iexxD0XPbD/Vi6KXGGdBvMt5+8AAs8PJHBb7al1j+RCXkQwpHntLqWCI0JRXwlbxTBciq" +
//                "FGlElCQJBAOGvCIrN6eG+OaIFQGk2Gck17qjNJKfP0AVnXPY2nm/0Pm+3rzX77j2KYdoXl33bz9J6dU0wocwh3DxWz/z+L70CQQDKrh" +
//                "4bhvNxBwIibT6FgVy3RTRouIKNoS4lhX2SnIhGzPumR6Z4NRETfpYbWP/QmpSOW8ldEhyw+j1vP7sXmdxzAkEA1egV+6IiLQIlFClQH" +
//                "KjXlfwVYk9Wj+wLqiOHXCL21vw0daUvX8aS0CeqiZFU2EkQ2NmS9v/CS35IhbRu3Md8LQJBAMUVIKOlyyz6IqI1VlldnDl96uN1n0V3" +
//                "GLdVofChk4Y9Jureu0oiV/N74RzAoyhGV/RB3oFI7mtNOdXmw9fEPm8CQQCcdFP1HpPABAUUKpZ2mXW1oSl8nBmMj0hbc8YpBs65HSk" +
//                "9eLw4tPqMLgIaLyd6rvFY6wQcmE0eDnJkB11TvVhG";
//		// byte[] bytes1 = RSAUtils.encryptByPublicKey(str.getBytes(), publicKey);
//		// byte[] bytes2 = RSAUtils.decryptByPrivateKey(bytes1, privateKey);
//
//		byte[] bytes3 = RSAUtils.decryptByPrivateKey(Base64Utils.decode(
//				"LO0QckOUqHXMuM2m46Jspk/N47/tOoax/wQfoJBhaeTBn3fn/lgoU9wjpQYLg7gvdWzj+F1YbXbkDpQYz1blwJwkK/" +
//                        "lAAZE6Ev6+Nwtll0HlYTkyS0u2xcFeHuaXPd9OpZnR4vkfLWYsEtF2xQ+b+6C99i29TwQv+PnptMYCfhWl+U+b20" +
//                        "jwVRYrKpHM5G7nNTkVZWjMjoW4B2z/Ur3QbVvTzhbqjDI/bvLyaGevsxEI8vBSk0mMNiYdvp7/CyvWjlNB6N8NW5DEF" +
//                        "aZYSwV4pQKkdBfx3wG1K2PgMrAS+n/b4L5oFkQEkj6TGqwhPEZ9wF9gOViWAr2AMjdwPSiBokautYh+pMoNwB5i1WU5" +
//                        "rHUcx/00rGdwWQXw9HSp3g6VlhbcYFfvNHYH8ISzhNQaHDA7VRfg/jLjKLZ9FNqI58d7sF7jAUYKtCPqdckxbhN3YRS" +
//                        "tJuXkUBydkHNFXu8XBl9YjfIicdYj+aWQZzrzlSclWKt6E4ze5E63vnp8de51SoPZNU4t/7J83+uld8z2281pjdWe2wn" +
//                        "CyVrPBSiabLCL89SUM9CsnOK11IfrlQfbPiJGNf+WiVZiCzMffK5N55e1HRZztnr8eW1VJhYLWiUDWb+qgpzlseyiEZ" +
//                        "812gSqNuqGcnbPIyRO4PNNsA0xvdkXKGu0ou235+UBzY44unMfgVVpp4EnqBFXdiJJxm1jFYx3ZoAzP6tlr6St7gtVlu/" +
//                        "qYZsiD9r5+Vy4awkFPl1/RUtk/WcfyyxF9jmZv2L9zbM/2ZYSg7Kbs/Ow2IVKFVBc/J07OfkJgOFD5SeRtd/Wfgn0F5i5" +
//                        "HeNcvHe7VwuvSy4jf7kSmiqW0iyyOtey1ATTKgLU6scHiN9IfIWcrTquSr5wn+SrYKf//PYBA+xTs20NbjnWEtzXEZQ9E" +
//                        "0CNN/Ll41ob4QlQ895PclazLPD1My/g6ugThdbO4QHm75gDn6427iHgRBHJqlJAATTk3MHh7omqWODiUcxcx+K7d098gH" +
//                        "1A8asvHSaXPoU5ybOjnWEKtdTL4wA6JNhrgGDosahgJnXGhV1vkw60pS7jPYTS2PmSMa7y+n48jpN1/za5DEy2ZuIssAX" +
//                        "7H1bdWNwubT2oSBhA1sADr+e00sE2uVC0+mh77vpRb4k6FjC1mX+9NzT+nJSthBGCupqSqatFWuluocYpnv5ztOWozp9hq" +
//                        "DZH2u9kmKrEJCwRKanVTJWQg/ZNIKW67s1jx6AhurVcV3L58gn3t915VlMLTE9U1bovFaV5GWC9ud99hph0PLZ8Gx7m4vu" +
//                        "DMcOecwB3sutY1sivSIKrW97MdiCjDCsUvyDSOWdDUHjlUD3F0Np1Mlk4HwnmfKl4TMhjITdSXNXlhQKY+ECgWnPLDfisn" +
//                        "vefiuoP4zIZIIkf23ms1NgmZLKWs2fNRkGvkXzqThe9l+ce4K1htqBQOgw+Lr8HKYO69waRKV2KzCCxppdeIv3koZpvc4DD" +
//                        "mErXfzdS3s+QPVEEvwEEMRdiEJ1Y7WUP7mGyLpEjt3NM1o4LHFO91RJPU6yqo7UoxNEdh5drqx8wesuG/31GNfB2/PqtJi" +
//                        "+ZquSqR0FQ9lmYaTJmpw8hPrcP0XDQNFyjUOtXH3Jd39noR5v+tkv9t6SjT0fMeqS0OBhtD1KOYV2xcuUoMQvN9ZCvtMGYmf" +
//                        "yNbNWgep2KDzKUSZrZYd2HLZegqROwbR4mObyEbXQ/WeEd9iSlEDLRqr0lg4v+Cl20y5I0LB5pgh8n3iQdTAmRBoYC5JjZf" +
//                        "UIQwdhakEpjp2tCm+wqajji+VWK8ZFstue3gRwOcSvAqIYAsknNkB1jrR7pGmop3s+kkYGBQbZAJgwAHu/dg3AKzfGqDKrb" +
//                        "OSM5+YmR3pe7pyYV6pTxaVb7ViQlZACW0jCwI5eKI698OMyYQKHG80dOKxEP/cLP0aDo1R84SO6/g8qemlmo9xmkHgu0hIhi/" +
//                        "eTW7P56FMRteA2PCj6JB5yKj5sP0r9yKAp0696GEuLtqpyc3GRMUyXhijWN4eCDPPPzw2LbIMWtNkCgTIHgaPoOT+EsLWAy" +
//                        "OtdTYEAgsr1CYnpABt1SGF4/sZPPNcRX3DZJiNzUlPgXSwPT4cI6qFUieCFer1N9TeVSoSPMXLqlU9Col1IaWEUrmyIj3D7" +
//                        "Q66VZNRZq3gFPiOc62I2Aq0oyk7f/AFmaxeUqPIv4iIYg7Z6DDAHEsoDxtACqk3PVDYcYI2JisLmn5/E8AcbEiRqmqTrLg1" +
//                        "epTPgCZOp8HGiBqMDKs+TUUM0/V3rGLEIsbNaTThVIb2HcoSUgp3bzpdoQhbBMj8bo2ZfaZtxn++Vd7MrmhL9WZAcXoB+o" +
//                        "DEF1ti2cSAg6y9nQrLB+W1n8IdVv1JZoC/ZBb0tZfqczR5zZRnFXzyCeXxdJvtMFCeB1Auae03DANnx4DCkAqHRyrcTSqQJ5" +
//                        "ys+BeuJOuaoX550Icvy1s3LgtmTXCaZkchOPIzUGSCzBWKSbq0pp9yW2flEvN8afT+fybfNQl88Kq10OSL0tlxQDFCQjIAds" +
//                        "0bmjO8hQyHifvxj0ITiGUionaN5rdQ3ULOYcWFpGZrLICpHu4mG2OoItTPl6J4lFmsXoix3XtEqOBqw05jy3DjAcZP/VNRTU" +
//                        "XUKlcLXU2gYt6bNthewL65mi0R2WFkG2SMe4Nr3nVjzWiqipIP8BW5r389B6eXf3YmAaMtpxl655FkAfzG463xJ1EbwBW+JPi" +
//                        "GYJnstAalXLNxqM7U0UduB31R79U6T8/W1VbC/IJtIe3Gq8g0XMHvcJ9wps0veBmUJcPZAqJVyk1VktzjaRI/Ug8ZC99IWKU" +
//                        "+u245Yr/P5C7qYJNDERt0fokIlaX/lx7vpC6G7BERXFE4JqtSOrlS/K6GzqjS4l/5Hb4pYF62l5chdfMYyrghRCN3aBmAKd6" +
//                        "xaAY5LDuk2zIPlfY2KO0lEr63/76tlLxpKMb3V0OZWv/RW5gbUtDgQaJvI5FuMgXIFibHjZaFdkbF6p6Ct/YJ+7YoFRnjWQ4" +
//                        "Ynb+gGRjCk1lj0NqeQ7GGrKrnxlVwF7J92g4aXN8usyS4TBY0gc0ZeB/3Z/O5qiH3V+"),
//				privateKey);

		// System.out.println();
		// System.out.println("****** 公钥加密 私钥解密 start ******");
		// System.out.println("加密前长度 ：" + str.toString().length());
		// System.out.println("加密后 ：" + Base64.encodeBase64String(bytes1));
		// System.out.println("解密后 ：" + new String(bytes2));
		// System.out.println("解密后长度 ：" + new String(bytes2).length());
		// System.out.println("****** 公钥加密 私钥解密 end ******");

		//System.out.println("解密后3 ：" + new String(new String(bytes3).getBytes(), "UTF-8"));
	//}
}
